package com.macken.wowoadmin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.macken.wowadmin.dao.HostDao;
import com.macken.wowadmin.entity.HostInfo;

@Controller
@RequestMapping("/host/")
public class HostController {
	HostDao hostDao = HostDao.instance;


	@RequestMapping("index.do")
	public String index(HttpServletRequest request) {
		List<HostInfo> hosts = hostDao.getHostList();
		request.setAttribute("hosts", hosts);
		return "/host/host.jsp";
	}

	@RequestMapping("add.do")
	public String add() {
		return "/host/addhost.jsp";
	}

	@RequestMapping("modify.do")
	public String modify(HttpServletRequest request, @RequestParam int hostid) {
		HostInfo host = hostDao.getHostById(hostid);
		request.setAttribute("host", host);
		return "/host/addhost.jsp";
	}

	@RequestMapping("del.do")
	public void del(HttpServletResponse response, @RequestParam int hostid) throws Exception {
		hostDao.del(hostid);
		response.sendRedirect("/host/index.do");
		return;
	}

	@RequestMapping("save.do")
	public void save(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(defaultValue = "-1") String hostid, @RequestParam String ip, @RequestParam int port,
			@RequestParam(defaultValue = "") String note) throws Exception {
		boolean isAdd = true;
		HostInfo host;
		if (hostid.equals("-1") || hostid.trim().equals("")) {
			host = new HostInfo();
		} else {
			int id = Integer.valueOf(hostid);
			host = hostDao.getHostById(id);
			if (host == null) {
				host = new HostInfo();
			} else {
				isAdd = false;
			}
		}
		host.setIp(ip);
		host.setPort(port);
		host.setNote(note);
		if (isAdd) {
			hostDao.add(host);
		} else {
			hostDao.update(host);
		}
		response.sendRedirect("/host/index.do");
		return;

	}
}
